package com.wakala.employment.fragment.trending;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.stx.xmarqueeview.XMarqueeView;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.interfaces.OnSimpleListener;
import com.wakala.employment.R;
import com.wakala.employment.adapter.ItemClickListener;
import com.wakala.employment.adapter.RecruitManageListAdapter;
import com.wakala.employment.adapter.bean.JobInfoPage;
import com.wakala.employment.adapter.bean.JobInfoSearchRequest;
import com.wakala.employment.adapter.entity.JobInfoVo;
import com.wakala.employment.adapter.marquee.MarqueeViewAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.bean.EventKey;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.core.tabbar.ContentPage;
import com.wakala.employment.databinding.FragmentRecruitmentBinding;
import com.wakala.employment.fragment.finder.JobDetailFragment;
import com.wakala.employment.fragment.recruit.RecruitIssueFragment;
import com.wakala.employment.http.TestApi;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.rxutil2.rxbus.RxEvent;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.tabbar.TabSegment;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.app.AppUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.functions.Consumer;

/**
 * 管理招工
 * A simple {@link Fragment} subclass.
 * Use the {@link RecruitmentFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class RecruitmentFragment extends BaseFragment<FragmentRecruitmentBinding> implements View.OnClickListener {
    private static String TAG= RecruitmentFragment.class.getSimpleName();
    TabSegment mTabSegment1;
    String[] pages = ContentPage.getPageNames();

    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;

    private RecruitManageListAdapter mRecruitInfoListAdapter;

    int page = 1;
    int pageSize = 10;

    /**
     * jonInfo查询条件
     */
    private JobInfoSearchRequest jobInfoSearchRequest = new JobInfoSearchRequest();

    @NonNull
    @Override
    protected FragmentRecruitmentBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentRecruitmentBinding.inflate(inflater, container, attachToRoot);
    }


    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        requireActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return null;
    }

    @Override
    protected void initViews() {
        binding.lyTitle.setZ(Float.MAX_VALUE);
        //-------顶部微信模块
        List<String> data = new ArrayList<>();
        data.add("免费加入本地招人找活群");
        data.add("附件找人找活信息推送");
        data.add("优质创业项目推荐");
        data.add("超多赚钱机会分享");

        XMarqueeView xMarqueeView = (XMarqueeView) findViewById(R.id.marquee);
        try {
            xMarqueeView.setAdapter(new MarqueeViewAdapter(data, getContext()));
        } catch (Exception e) {
            //catchsetAdapter重复设置adapter抛出异常的异常。
            Log.w("", e.getMessage());
        }
        binding.rbWeiChat.setOnClickListener(view -> {
            //打开关注微信界面
            if (AppUtils.isInstallApp("com.tencent.mm")) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("weixin://dl/officialaccount?officialAccountID=" + "miaoyankeji"));
                    startActivity(intent);
                } catch (Exception e) {
                    // 处理异常情况
                    PopTip.show("打开微信失败");
                }
            } else {
                PopTip.show("本机没有安装微信");
            }
        });
        //---
        // TabSegment
        mTabSegment1 = binding.tabSegment1;
        recyclerView = binding.recyclerView;
        refreshLayout=binding.refreshLayout;
        initNoViewPagerTabSegment();
        //
        WidgetUtils.initRecyclerView(recyclerView, DensityUtils.dp2px(getContext(), 5), ThemeUtils.resolveColor(getContext(), R.attr.xui_config_color_background));

        recyclerView.setAdapter(mRecruitInfoListAdapter = new RecruitManageListAdapter(false,recyclerViewItemClickListener));
        //-------------
    }
    @Override
    protected void initListeners() {
        super.initListeners();
        binding.fabBtnPub.setOnClickListener(this);
        //-------------
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            int currentPage = mRecruitInfoListAdapter.getItemCount() / pageSize + 1;
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                jobInfoSearchRequest.setPage(currentPage+1);
                getJobInfoList("more");
            }

            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                jobInfoSearchRequest.setPage(1);
                getJobInfoList("fresh");
            }
        });

        mRecruitInfoListAdapter.setOnItemClickListener((itemView, item, position) -> {
            handlerItemDetailClick(item);

        });

        //设置刷新加载时禁止所有列表操作
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.autoRefresh();
        //
        RxBusUtils.get().on(EventKey.EVENT_BACK_NORMAL+"_job_detail", RxEvent.class, new Consumer<RxEvent>() {
            @Override
            public void accept(RxEvent event) throws Exception {
                //RxToast.success("事件key:"+EventKey.EVENT_HAVE_DATA);
                XUtil.runOnUiThread(() -> getJobInfoList("fresh"));
            }
        });
    }

    /**
     * recyclerView item点击事件
     */
    private final ItemClickListener<JobInfoVo> recyclerViewItemClickListener = new ItemClickListener<JobInfoVo>() {

        @Override
        public void onItemClick(RecyclerViewHolder holder,View view, JobInfoVo model, int position) {
            if(view.getId()==R.id.tv_close){
                handlerItemCloseClick(model);
            }else if(view.getId()==R.id.tv_edit){
                handlerItemModifyClick(model);
            }else if(view.getId()==R.id.tv_refresh){
                handlerItemRefreshClick(model);
            }else if(view.getId()==R.id.tv_to_top){
                handlerItemSetTopClick(model);
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBusUtils.get().unregisterAll(EventKey.EVENT_BACK_NORMAL+"_job_detail");
    }

    /**
     * 职位详情
     * @param item
     */
    private void handlerItemDetailClick(JobInfoVo item){
        openNewPage(JobDetailFragment.class,"jobInfoId",item.getId());
    }

    /**
     * 关闭职位
     * @param item
     */
    private void handlerItemCloseClick(JobInfoVo item){

        MessageDialog messageDialog = new MessageDialog("系统提示", "关闭职位后，不会再有工人联系您，确认关闭吗？", "确定", "取消")
                .setButtonOrientation(LinearLayout.VERTICAL);
        messageDialog.setStyle(com.kongzue.dialogx.style.MIUIStyle.style());
        messageDialog.setOkButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog messageDialog, View view) {
                closeJobInfo(item.getId());
                return false;
            }
        });
        messageDialog.setCancelButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog messageDialog, View view) {
                // PopTip.show("取消"+item.getTitle());
                return false;
            }
        });
        messageDialog.show();
    }

    /**
     * 职位修改
     * @param item
     */
    private void handlerItemModifyClick(JobInfoVo item){
        //PopTip.show("修改"+item.getTitle());
        openNewPage(RecruitIssueFragment.class,"edit-data",item);
    }

    /**
     * 刷新职位
     * @param item
     */
    private void handlerItemRefreshClick(JobInfoVo item){
        PopTip.show("刷新"+item.getTitle());
    }

    /**
     * 置顶职位
     * @param item
     */
    private void handlerItemSetTopClick(JobInfoVo item){
        PopTip.show("置顶"+item.getTitle());
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.fab_btn_pub){
            //发布职位
            openNewPage(RecruitIssueFragment.class);
        }

    }

    /**
     * 不使用ViewPager的情况
     */
    private void initNoViewPagerTabSegment() {
        for (String page : pages) {
            mTabSegment1.addTab(new TabSegment.Tab(page));
        }
        mTabSegment1.setMode(TabSegment.MODE_FIXED);
        mTabSegment1.setOnTabClickListener(index -> {
            //XToastUtils.toast("点击了" + index)
            if(index==0){
                jobInfoSearchRequest.setStatus(null);
            } else if (index==1) {//招聘中
                jobInfoSearchRequest.setStatus(Integer.valueOf(Constants.JOB_STATUS_RUNNING));
            } else if (index==2) {//审核中
                jobInfoSearchRequest.setStatus(Integer.valueOf(Constants.JOB_STATUS_AUTHING));
            } else if (index==3){ //已完成/已招满
                jobInfoSearchRequest.setStatus(Integer.valueOf(Constants.JOB_STATUS_FINISHED));
            }
            getJobInfoList("fresh");

        });
        //不使用ViewPager的话，必须notifyDataChanged，否则不能正常显示
        mTabSegment1.notifyDataChanged();
        mTabSegment1.selectTab(0);
        mTabSegment1.addOnTabSelectedListener(new TabSegment.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int index) {
                if (mTabSegment1 != null) {
                    mTabSegment1.hideSignCountView(index);
                }
            }

            @Override
            public void onTabUnselected(int index) {

            }

            @Override
            public void onTabReselected(int index) {
                if (mTabSegment1 != null) {
                    mTabSegment1.hideSignCountView(index);
                }
            }

            @Override
            public void onDoubleTap(int index) {

            }
        });

    }
    /**
     * 查询招聘信息列表数据
     *
     * @return
     */
    @SuppressLint("CheckResult")
    private void getJobInfoList(String mode) {
        //binding.llStateful.showLoading();
        appLoadingDialog.show();
        jobInfoSearchRequest.setLimit(pageSize);
        XHttpProxy.proxy(TestApi.IJobService.class)
                .jobInfList2User(jobInfoSearchRequest)
                .subscribeWith(new NoTipRequestSubscriber<JobInfoPage>() {
                    @Override
                    protected void onSuccess(JobInfoPage commonPageApiResult) {
                        Log.i(TAG, "-------------招聘信息列表------------------");
                        Log.i(TAG, GsonUtils.toJson(commonPageApiResult));
                        if("fresh".equals(mode)){
                            mRecruitInfoListAdapter.refresh(commonPageApiResult.getList());
                            refreshLayout.finishRefresh();
                            Toaster.show("信息列表已刷新");
                        } else if ("more".equals(mode)) {

                            if(commonPageApiResult.getList().isEmpty()){
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                ToastUtils.toast("已更新到最新数据");
                            }else {
                                mRecruitInfoListAdapter.loadMore(commonPageApiResult.getList());
                                refreshLayout.finishLoadMore();
                            }

                        }
                        appLoadingDialog.dismiss();
                        //binding.llStateful.showContent();
                        //ToastUtils.toast("已更新最新数据");
                        Log.i(TAG, "-------------招聘信息列表------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        binding.refreshLayout.finishRefresh();
                        ToastUtils.toast(e.getDisplayMessage());
                        /*binding.llStateful.showError("加载数据失败", "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                getJobInfoList();
                            }
                        });*/
                        appLoadingDialog.dismiss();
                        Log.i(TAG, "-------------招工信息列表-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });

    }
    @SuppressLint("CheckResult")
    private void closeJobInfo(Long jobInfoId) {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IJobService.class)
                .closeJobInfo(jobInfoId)
                .subscribeWith(new NoTipRequestSubscriber() {
                    @Override
                    protected void onSuccess(Object object) {
                        Log.i(TAG, "-------------关闭招工------------------");
                        appLoadingDialog.dismiss();
                        Toaster.show("招工信息已关闭");
                        RxTool.delayToDo(2000, new OnSimpleListener() {
                            @Override
                            public void doSomething() {
                                popToBack();
                                RxBusUtils.get().postRxEvent(EventKey.EVENT_BACK_NORMAL+"_job_detail");
                            }
                        });

                        Log.i(TAG, "-------------关闭招工------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                        appLoadingDialog.dismiss();
                        Log.i(TAG, "-------------关闭招工-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }
                });
    }
}